
import com.wxc.list.AbsList;

import java.util.Arrays;

/**
 * @program: LoveDataStructures1
 * @description: 动态数组
 * @author: wxc
 * @create: 2021-04-03 15:02
 **/
@SuppressWarnings("unchecked")
public class MyArray<E> extends AbsList<E> {
    private E[] elements;
    private static final int DEFAULT_CAPACITY = 5;

    public MyArray(int capacity) {
        if (capacity <= DEFAULT_CAPACITY) {
            capacity = DEFAULT_CAPACITY;
        }
        this.elements = (E[]) new Object[capacity];
    }

    public MyArray() {
        this(DEFAULT_CAPACITY);
    }

    public E get(int index) {
        rangeCheck(index);

        return elements[index];
    }

    public E set(int index, E element) {
        rangeCheck(index);

        E oldElement = elements[index];
        elements[index] = element;
        return oldElement;
    }

    public void add(int index, E element) {
        rangeCheckForAdd(index);
        // 检查容量
        ensureCapacity(size + 1);
        for (int i = size; i > index; i--) {
            elements[i] = elements[i - 1];
        }
        elements[index] = element;
        size++;
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        // 扩容
        if (capacity > oldCapacity) {
            // 新容量
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            E[] newElements = (E[]) new Object[newCapacity];
            // 循环赋值
            for (int i = 0; i < size; i++) {
                newElements[i] = elements[i];
            }
            elements = newElements;
        }
    }

    public E remove(int index) {
        rangeCheckForAdd(index);

        E removeElem = elements[index];
//        for (int i = index; i < size - 1; i++) {
//            elements[i] = elements[i + 1];
//        }
        for (int i = index + 1; i < size; i++) {
            elements[i - 1] = elements[i];
        }
        // 把最后一个元素设成null
        elements[--size] = null;
        return removeElem;
    }

    public int indexOf(E element) {
        // 分开处理为空的情况
        if (element == null) {
            for (int i = 0; i < size; i++) {
                if (elements[i] == null) return i;
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (element.equals(elements[i])) return i;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    public void clear() {
        for (int i = 0; i < size; i++) elements[i] = null;
        size = 0;
    }

    @Override
    public String toString() {
        return "MyArray{" +
                "size=" + size +
                ", elements=" + Arrays.toString(elements) +
                '}';
    }
}

